#!/usr/bin/env python

from Cookie import SimpleCookie

def getCookie(handle, value, key):
    try:
        data = handle.request.cookies[key]
        if not data:
            data = None
    except:
        data = None
        
     
    #get value, value is not null
    if value:
        if data is not None:
            if data != value:
                setCookie(handle, value, key)
                _value = value
            else:                
                _value = data            
        else:
            setCookie(handle, value, key)
            _value = value
            
    #get value, value is null
    else:
        if data is not None:
            _value = data
        else:
            _value = None
    
    return _value

def setCookie(handle, value, key, max_age=365*24*60*60):
    c = SimpleCookie()
    c[key] = value
    c[key]['max-age'] = max_age
    header_value = c[key].output(header='').lstrip()
    handle.response.headers._headers.append(('Set-Cookie', header_value))
